import { ref, onMounted, watch } from 'vue';
import { Camera, CameraResultType, CameraSource, Photo } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Preferences } from '@capacitor/preferences';
import { isPlatform } from '@ionic/vue';
import { Capacitor } from '@capacitor/core';

// HarmonyOS 平台检测
const isHarmonyOS = (): boolean => {
  // 检查是否在 HarmonyOS 环境中
  return !!(window as any).HarmonyOS || 
         navigator.userAgent.includes('HarmonyOS') ||
         (window as any).HarmonyBridge;
};

export function usePhotoGallery() {
  const photos = ref<UserPhoto[]>([]);
  const PHOTO_STORAGE = 'photos';

  const takePhoto = async () => {
    try {
      let photo: Photo;
      
      if (isHarmonyOS()) {
        // HarmonyOS 平台使用原生桥接
        photo = await takePhotoHarmonyOS();
      } else {
        // 其他平台使用 Capacitor Camera
        photo = await Camera.getPhoto({
          resultType: CameraResultType.Uri,
          source: CameraSource.Camera,
          quality: 90,
          // Web 平台特定配置
          ...(isPlatform('desktop') && {
            width: 600,
            height: 600
          })
        });
      }

      const fileName = Date.now() + '.jpeg';
      const savedFileImage = await savePicture(photo, fileName);
      photos.value = [savedFileImage, ...photos.value];
    } catch (error) {
      console.error('拍照失败:', error);
      // 平台特定错误处理
      if (isPlatform('desktop')) {
        alert('相机功能在此浏览器中不可用，请尝试使用支持的浏览器');
      } else if (isHarmonyOS()) {
        alert('相机功能暂时不可用，请检查相机权限');
      }
    }
  };

  // HarmonyOS 平台拍照实现
  const takePhotoHarmonyOS = async (): Promise<Photo> => {
    const harmonyBridge = (window as any).HarmonyOS?.Plugins?.Camera;
    if (!harmonyBridge) {
      throw new Error('HarmonyOS Camera bridge not available');
    }

    const options = {
      quality: 90,
      allowEdit: false,
      resultType: 'uri',
      source: 'camera'
    };

    const result = await harmonyBridge.getPhoto(options);
    return {
      webPath: result.webPath,
      path: result.webPath,
      format: 'jpeg',
      saved: false  // Add the missing saved property
    };
  };

  const savePicture = async (photo: Photo, fileName: string): Promise<UserPhoto> => {
    let base64Data: string;
    
    if (isHarmonyOS()) {
      // HarmonyOS 平台处理
      base64Data = await saveFileHarmonyOS(photo, fileName);
      return {
        filepath: fileName,
        webviewPath: photo.webPath
      };
    } else if (isPlatform('hybrid')) {
      // 移动平台处理
      const file = await Filesystem.readFile({
        path: photo.path!
      });
      base64Data = file.data as string;
    } else {
      // Web 平台处理
      base64Data = await base64FromPath(photo.webPath!);
    }

    const savedFile = await Filesystem.writeFile({
      path: fileName,
      data: base64Data,
      directory: Directory.Data
    });

    if (isPlatform('desktop')) {
      // Web 平台返回 Capacitor 内部 URL
      return {
        filepath: fileName,
        webviewPath: photo.webPath
      };
    } else {
      // 移动平台使用 Capacitor.convertFileSrc 转换文件路径
      return {
        filepath: fileName,
        webviewPath: Capacitor.convertFileSrc(savedFile.uri),
      };
    }
  };

  // HarmonyOS 平台文件保存
  const saveFileHarmonyOS = async (photo: Photo, fileName: string): Promise<string> => {
    const harmonyBridge = (window as any).HarmonyOS?.Plugins?.Filesystem;
    if (!harmonyBridge) {
      throw new Error('HarmonyOS Filesystem bridge not available');
    }

    // 读取照片数据
    const fileData = await fetch(photo.webPath!);
    const blob = await fileData.blob();
    const base64Data = await blobToBase64(blob);

    // 保存到 HarmonyOS 文件系统
    await harmonyBridge.writeFile({
      path: fileName,
      data: base64Data
    });

    return base64Data;
  };

  // Blob 转 Base64 辅助函数
  const blobToBase64 = (blob: Blob): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onerror = reject;
      reader.onload = () => {
        if (typeof reader.result === 'string') {
          resolve(reader.result);
        } else {
          reject(new Error('无法读取文件'));
        }
      };
      reader.readAsDataURL(blob);
    });
  };

  // Web 平台 base64 转换辅助函数
  const base64FromPath = async (path: string): Promise<string> => {
    const response = await fetch(path);
    const blob = await response.blob();
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onerror = reject;
      reader.onload = () => {
        if (typeof reader.result === 'string') {
          resolve(reader.result);
        } else {
          reject(new Error('无法读取文件'));
        }
      };
      reader.readAsDataURL(blob);
    });
  };

  const loadSaved = async () => {
    let photosInPreferences: UserPhoto[] = [];

    if (isHarmonyOS()) {
      // HarmonyOS 平台加载
      photosInPreferences = await loadSavedHarmonyOS();
    } else {
      // 其他平台加载
      const { value } = await Preferences.get({ key: PHOTO_STORAGE });
      photosInPreferences = value ? JSON.parse(value) : [];

      if (!isPlatform('hybrid')) {
        for (const photo of photosInPreferences) {
          const file = await Filesystem.readFile({
            path: photo.filepath,
            directory: Directory.Data,
          });
          photo.webviewPath = `data:image/jpeg;base64,${file.data}`;
        }
      }
    }

    photos.value = photosInPreferences;
  };

  // HarmonyOS 平台加载已保存的照片
  const loadSavedHarmonyOS = async (): Promise<UserPhoto[]> => {
    try {
      const harmonyBridge = (window as any).HarmonyOS?.Plugins?.Filesystem;
      if (!harmonyBridge) {
        return [];
      }

      const result = await harmonyBridge.readFile({
        path: PHOTO_STORAGE + '.json'
      });

      const photosData = JSON.parse(result.data);
      
      // 为每张照片加载实际的图片数据
      for (const photo of photosData) {
        try {
          const imageData = await harmonyBridge.readFile({
            path: photo.filepath
          });
          photo.webviewPath = `data:image/jpeg;base64,${imageData.data}`;
        } catch (error) {
          console.warn('Failed to load photo:', photo.filepath, error);
        }
      }

      return photosData;
    } catch (error) {
      console.warn('Failed to load saved photos from HarmonyOS:', error);
      return [];
    }
  };

  const cachePhotos = () => {
    if (isHarmonyOS()) {
      // HarmonyOS 平台缓存
      cachePhotosHarmonyOS();
    } else {
      // 其他平台缓存
      Preferences.set({
        key: PHOTO_STORAGE,
        value: JSON.stringify(photos.value),
      });
    }
  };

  // HarmonyOS 平台缓存照片
  const cachePhotosHarmonyOS = async () => {
    try {
      const harmonyBridge = (window as any).HarmonyOS?.Plugins?.Filesystem;
      if (!harmonyBridge) {
        return;
      }

      await harmonyBridge.writeFile({
        path: PHOTO_STORAGE + '.json',
        data: JSON.stringify(photos.value)
      });
    } catch (error) {
      console.error('Failed to cache photos on HarmonyOS:', error);
    }
  };

  watch(photos, cachePhotos);

  onMounted(() => {
    // 等待 HarmonyOS 桥接准备就绪
    if (isHarmonyOS()) {
      const checkBridge = () => {
        if ((window as any).HarmonyOS?.bridge) {
          loadSaved();
        } else {
          setTimeout(checkBridge, 100);
        }
      };
      
      // 监听 HarmonyOS 就绪事件
      document.addEventListener('harmonyos-ready', () => {
        loadSaved();
      });
      
      checkBridge();
    } else {
      loadSaved();
    }
  });

  return {
    photos,
    takePhoto,
    isHarmonyOS: isHarmonyOS()
  };
}

export interface UserPhoto {
  filepath: string;
  webviewPath?: string;
}
